package com.hmitkov.musicplayer;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.os.Environment;

public class SongsManager {
	public static final SongsManager instance = new SongsManager();
	// SDCard Path
	File musicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
	private ArrayList<HashMap> songsList = null;
	public File[] files;

	// Constructor
	private SongsManager() {
	}

	/**
	 * Function to read all mp3 files from sdcard and store the details in
	 * ArrayList
	 * */
	public ArrayList<HashMap> getPlayList(Context c) {
		songsList = new ArrayList<HashMap>();
		files = musicDir.listFiles();
		if (files == null || files.length == 0) {
			try {
				String[] assets = c.getAssets().list("songs");
				for (String asset : assets) {
					HashMap song = new HashMap();
					song.put("songTitle", asset);
					song.put("songPath", c.getAssets().openFd("songs/" + asset));
					songsList.add(song);
				}
			} catch (Exception e) {
				new AlertDialogManager().showAlertDialog(c, "Error!", e.getMessage(), false);
			}
		} else if (musicDir.listFiles(new FileExtensionFilter()).length > 0) {
			for (File file : musicDir.listFiles(new FileExtensionFilter())) {
				HashMap<String, String> song = new HashMap<String, String>();
				song.put("songTitle", file.getName());
				song.put("songPath", file.getPath());

				// Adding each song to SongList
				songsList.add(song);
			}
		}
		// return songs list array
		return songsList;
	}

	/**
	 * Class to filter files which are having .mp3 extension
	 * */
	class FileExtensionFilter implements FilenameFilter {
		public boolean accept(File dir, String name) {
			return (name.endsWith(".mp3") || name.endsWith(".MP3") || name.endsWith("mp4"));
		}
	}
}
